import * as types from '../mutation-types'
import {getTopicsList} from 'api/topics'
import moment from 'moment'

moment.locale('zh-cn')

const state = {
  indexValue: '',
  topicsList: []
}

// getters
const getters = {
  indexValue: state => state.indexValue,
  topicsList: state => state.topicsList
}

// actions
const actions = {
  // 获取话题列表
  TopicsList({commit}, tab) {
    return getTopicsList(tab).then((res) => {
      if (res.success === false) {
        return false
      } else {
        res.data.forEach((item) => {
          item.create_at = moment(item.create_at).startOf().fromNow()
          delete item.content
        })
        commit(types.SET_TOPICS_LIST, res.data)
        return true
      }
    })
  },
  // 加载更多话题列表
  MoreTopics({commit}, {tab, page}) {
    return getTopicsList(tab, page).then((res) => {
      if (res.success === false) {
        return false
      } else {
        res.data.forEach((item) => {
          item.create_at = moment(item.create_at).startOf().fromNow()
          delete item.content
        })
        commit(types.SET_TOPICS_LIST, state.topicsList.concat(res.data))
        return true
      }
    })
  }
}

// mutations
const mutations = {
  [types.SET_INDEX_VALUE](state, val) {
    state.indexValue = val
  },
  [types.SET_TOPICS_LIST](state, list) {
    state.topicsList = list
  }
}

export default {
  state,
  getters,
  actions,
  mutations
}
